package demo2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpClient {
    DatagramSocket socket = null;
    public UdpClient() throws SocketException {
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动!!!");
        while(true){
            Scanner scan = new Scanner(System.in);
            System.out.print(">");
            String request = scan.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName("127.0.0.1"),8000);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("request : %s ; response : %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient udpClient = new UdpClient();
        udpClient.start();
    }
}
